﻿Public Class FrmVenta
    Dim acceso As New acceso_a_datos
    Dim combo As New combo
    Protected tablaArticulo As New Data.DataTable

    Private Sub FrmVenta_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        cargarCombo()
        combo.cargar(cmbTipoDoc, "TipoDNI")
        combo.cargar(cmbVendedor, "Empleado")
    End Sub

    Private Sub cargarCombo()
        Dim mySource As New AutoCompleteStringCollection()
        Dim tablaArticulos As New Data.DataTable

        tablaArticulos = acceso._consulta("SELECT a.nombre, t.Descripcion FROM Articulo a, TipoArticulo t WHERE a.idTipoArticulo=t.idTipoArticulo")
        Dim nombres(tablaArticulos.Rows.Count) As String

        For i = 0 To tablaArticulos.Rows.Count - 1
            Dim valorArticulo As String = tablaArticulos(i)("nombre")
            Dim valorTipoArticulo As String = tablaArticulos(i)("Descripcion")
            nombres(i) = valorArticulo & " - " & valorTipoArticulo
            mySource.Add(nombres(i))
        Next

        With cmbTituloArticulo
            .AutoCompleteCustomSource = mySource
            .AutoCompleteMode = AutoCompleteMode.SuggestAppend
            .AutoCompleteSource = AutoCompleteSource.CustomSource
        End With
    End Sub

    Private Sub rdbTituloArticulo_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles rdbTituloArticulo.CheckedChanged, rdbCodigoBarrasArticulo.CheckedChanged
        cmbTituloArticulo.Enabled = rdbTituloArticulo.Checked
        mtxtCodBarrasArticulo.Enabled = rdbCodigoBarrasArticulo.Checked
        limpiarCamposArticulo()
    End Sub

    Private Sub mtxtNroDoc_KeyUp(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles mtxtNroDoc.KeyUp
        If e.KeyCode = Keys.Enter Then
            buscarCliente()
        End If
    End Sub

    Private Sub buscarCliente()
        If mtxtNroDoc.Text = "" Then
            Exit Sub
        End If
        Dim consulta As String = "SELECT apellidos, nombres FROM Cliente WHERE idTipoDNI=" & cmbTipoDoc.SelectedValue & " AND NroDNI= " & mtxtNroDoc.Text
        Dim tablaCliente As Data.DataTable = acceso._consulta(consulta)
        If tablaCliente.Rows.Count > 0 Then
            txtApellidos.Text = tablaCliente(0)("apellidos")
            txtNombres.Text = tablaCliente(0)("nombres")
        Else
            limpiarCliente()
            MsgBox("No existe el Cliente", MsgBoxStyle.Information, "Cliente Inexistente")
        End If
        mtxtCodBarrasArticulo.Focus()
    End Sub

    Private Sub mtxtCodBarrasArticulo_KeyUp(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles mtxtCodBarrasArticulo.KeyUp
        btnAgregar.Enabled = False
        If e.KeyCode = Keys.Enter Then
            If mtxtCodBarrasArticulo.Text.Trim = "" Then
                MsgBox("Ingrese un código de barras a buscar.", MsgBoxStyle.Critical, "Código de Barras Requerido")
                Exit Sub
            End If
            buscarArticulo()
        End If
    End Sub

    Private Sub buscarArticulo()
        Dim consulta As String = "SELECT a.idarticulo, a.codigoBarras, a.nombre, t.Descripcion, g.Descripcion, a.cantidadVenta, t.precioVenta, t.precioAlquiler FROM Articulo a, Genero g, TipoArticulo t WHERE "

        If rdbCodigoBarrasArticulo.Checked Then
            consulta += "a.codigoBarras=" & mtxtCodBarrasArticulo.Text
        Else
            If cmbTituloArticulo.SelectedText.Contains(" - ") Then
                consulta += "a.nombre='" & cmbTituloArticulo.SelectedText.Substring(0, cmbTituloArticulo.SelectedText.IndexOf(" - ")) & "'"
            Else
                consulta += "a.nombre='" & cmbTituloArticulo.SelectedText & "'"
            End If
        End If
        consulta += " AND a.idTipoArticulo=t.idTipoArticulo AND a.idGenero=g.idGenero"
        tablaArticulo = acceso._consulta(consulta)
        If tablaArticulo.Rows.Count > 0 Then
            If tablaArticulo(0).IsNull("codigoBarras") Then
                mtxtCodBarrasArticulo.Text = 0
            Else
                mtxtCodBarrasArticulo.Text = tablaArticulo(0)("codigoBarras")
            End If
            cmbTituloArticulo.SelectedText = tablaArticulo(0)("nombre") & " - " & tablaArticulo(0)("Descripcion")
            txtGenero.Text = tablaArticulo(0)("Descripcion1")
            Dim existe As Boolean
            For Each fila As DataGridViewRow In DataGridViewDatos.Rows
                If fila.Cells("colIdArticulo").Value.Equals(tablaArticulo(0)(0)) Then
                    Dim cantidad As Integer = fila.Cells("colCantidad").Value
                    txtCantidadDisponible.Text = tablaArticulo(0)("cantidadVenta") - cantidad
                    existe = True
                End If
            Next
            If Not existe Then
                txtCantidadDisponible.Text = tablaArticulo(0)("cantidadVenta")
            End If
            txtPrecio.Text = tablaArticulo(0)("precioVenta")
            txtCantidadVenta.Enabled = True
            txtCantidadVenta.Focus()
        Else
            mtxtCodBarrasArticulo.Text = ""
            cmbTituloArticulo.Text = ""
            MsgBox("No existe el Producto", MsgBoxStyle.Information, "Producto Inexistente")
            txtCantidadVenta.Enabled = False
            btnAgregar.Enabled = False
            If rdbCodigoBarrasArticulo.Checked Then
                mtxtCodBarrasArticulo.Focus()
            Else
                cmbTituloArticulo.Focus()
            End If
        End If
    End Sub

    Private Sub cmbTituloArticulo_KeyUp(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles cmbTituloArticulo.KeyUp
        If e.KeyCode = Keys.Enter Then
            buscarArticulo()
        End If
    End Sub

    Protected Sub limpiarCamposArticulo()
        mtxtCodBarrasArticulo.Text = ""
        cmbTituloArticulo.Text = ""
        txtGenero.Text = ""
        txtCantidadDisponible.Text = ""
        txtPrecio.Text = ""
        txtCantidadVenta.Text = ""
        txtSubTotal.Text = ""
        txtCantidadVenta.Enabled = False
        btnAgregar.Enabled = False
        If rdbCodigoBarrasArticulo.Checked Then
            mtxtCodBarrasArticulo.Focus()
        Else
            cmbTituloArticulo.Focus()
        End If
    End Sub

    Private Sub txtCantidadVenta_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles txtCantidadVenta.KeyPress
        If Char.IsDigit(e.KeyChar) Then
            e.Handled = False
            btnAgregar.Enabled = True
        ElseIf Char.IsControl(e.KeyChar) Then
            e.Handled = False
        Else
            e.Handled = True
        End If
    End Sub

    Private Sub txtCantidadVenta_KeyUp(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles txtCantidadVenta.KeyUp
        Dim valido = True
        If e.KeyCode = Keys.Enter Then
            If txtCantidadVenta.Text.Trim = "" Then
                valido = False
            ElseIf txtCantidadVenta.Text < 1 Then
                valido = False
            Else
                agregarDetalle()
            End If
        End If
        If Not valido Then
            MsgBox("Debe ingresar una cantidad mayor a cero", MsgBoxStyle.Critical, "Cantidad Inválida")
        End If
    End Sub

    Private Sub txtCantidadVenta_LostFocus(ByVal sender As Object, ByVal e As System.EventArgs) Handles txtCantidadVenta.LostFocus
        If Not txtCantidadVenta.Text.Trim = "" Then
            txtSubTotal.Text = txtPrecio.Text * txtCantidadVenta.Text
        End If
    End Sub

    Private Sub txtCantidadVenta_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles txtCantidadVenta.TextChanged
        If txtCantidadVenta.Text = "" Then
            btnAgregar.Enabled = False
        End If
    End Sub

    Private Sub btnAgregar_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnAgregar.Click
        agregarDetalle()
    End Sub


    Private Sub DataGridViewDatos_RowsAdded(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewRowsAddedEventArgs) Handles DataGridViewDatos.RowsAdded
        calcularTotal()
    End Sub

    Private Sub calcularTotal()
        Dim total As Double = 0
        For Each fila As DataGridViewRow In DataGridViewDatos.Rows
            total += fila.Cells("colSubTotal").Value
        Next
        txtTotal.Text = total
    End Sub

    Private Sub DataGridViewDatos_RowsRemoved(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewRowsRemovedEventArgs) Handles DataGridViewDatos.RowsRemoved
        If DataGridViewDatos.Rows.Count > 0 Then
            calcularTotal()
        Else
            txtTotal.Text = 0
            btnFinVta.Enabled = False
            btnCancelar.Enabled = False
        End If
        limpiarCamposArticulo()
    End Sub

    Private Sub agregarDetalle()
        Dim cv As Integer = txtCantidadVenta.Text
        Dim cd As Integer = txtCantidadDisponible.Text
        If cv > cd Then
            MsgBox("La cantidad a comprar supera a la cantidad en stock. Ingrese una cantidad menor.", MsgBoxStyle.Critical, "Stock Insuficiente")
            txtCantidadVenta.Focus()
            Exit Sub
        End If

        Dim existe = False
        For Each fila As DataGridViewRow In DataGridViewDatos.Rows
            If fila.Cells("colIdArticulo").Value.Equals(tablaArticulo(0)(0)) Then
                Dim cantidad As Integer = fila.Cells("colCantidad").Value
                cantidad += txtCantidadVenta.Text
                fila.Cells("colCantidad").Value = cantidad
                existe = True
            End If
        Next
        If Not existe Then
            DataGridViewDatos.Rows.Add(tablaArticulo.Rows(0)("idarticulo"), cmbTituloArticulo.Text, txtCantidadVenta.Text, txtPrecio.Text, Double.Parse(txtPrecio.Text) * Integer.Parse(txtCantidadVenta.Text))
        End If
        txtCantidadDisponible.Text = cd - cv
        limpiarCamposArticulo()
        btnFinVta.Enabled = True
        btnCancelar.Enabled = True
    End Sub

    Private Sub btnFinVta_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnFinVta.Click
        MsgBox("Total A Cobrar: $ " & txtTotal.Text, MsgBoxStyle.Information, "Total")

        acceso._tabla = "Venta"
        Dim consultaInsertVenta As String = "INSERT INTO Venta(Fecha, Legajo"

        If Not txtApellidos.Text = "" Then
            consultaInsertVenta = consultaInsertVenta & ", tipoDocCliente, nroDocCliente"
        End If

        consultaInsertVenta = consultaInsertVenta & ") VALUES( GetDate()," & cmbVendedor.SelectedValue

        If Not txtApellidos.Text = "" Then
            consultaInsertVenta = consultaInsertVenta & ", " & cmbTipoDoc.SelectedValue & ", " & mtxtNroDoc.Text
        End If
        consultaInsertVenta = consultaInsertVenta & ")"
        acceso._consulta(consultaInsertVenta)

        Dim idVenta As Data.DataTable = acceso._consulta("SELECT MAX(idVenta) FROM Venta")

        acceso._tabla = "DetalleVenta"
        For Each fila As DataGridViewRow In DataGridViewDatos.Rows
            Dim consultaInsertDetalleVenta As String = "INSERT INTO DetalleVenta VALUES(" & idVenta.Rows(0)(0) & ", " & fila.Cells(0).Value & ", " & fila.Cells(2).Value & ", " & fila.Cells(3).Value.ToString.Replace(",", ".") & ")"
            acceso._consulta(consultaInsertDetalleVenta)
            Dim consultaUpdateArticulo As String = "UPDATE Articulo SET cantidadVenta = cantidadVenta - " & fila.Cells(2).Value & " WHERE idarticulo = " & tablaArticulo.Rows(0)(0)
            acceso._consulta(consultaUpdateArticulo)
        Next
        MsgBox("Se registró la venta exitosamente", MsgBoxStyle.Exclamation, "Venta Realizada")
        limpiarCamposArticulo()
        limpiarCliente()
        limpiarGrilla()
        btnFinVta.Enabled = False
        btnCancelar.Enabled = False
        mtxtNroDoc.Focus()
    End Sub

    Protected Sub limpiarCliente()
        txtApellidos.Text = ""
        txtNombres.Text = ""
        mtxtNroDoc.Text = ""
        cmbTipoDoc.SelectedIndex = 0
    End Sub

    Private Sub limpiarGrilla()
        DataGridViewDatos.Rows.Clear()
    End Sub

    Private Sub btnCancelar_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCancelar.Click
        If MsgBox("Está por borrar los datos ingresados. ¿ Está seguro ?", MsgBoxStyle.Question + MsgBoxStyle.YesNo, "Cancelar") = MsgBoxResult.Yes Then
            limpiarCamposArticulo()
            limpiarCliente()
            limpiarGrilla()
            btnFinVta.Enabled = False
            btnCancelar.Enabled = False
        End If
    End Sub
End Class